﻿using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using EIIS.Infrastructure.Service.Business;
using EIIS.Infrastructure.Service.System;
using EIIS.Infrastructure.Model.Business;
using EIIS.Infrastructure.Model.System;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;
using EIIS.Infrastructure.Model.System.Authority;

namespace EIIS.Presentation.Controllers.Business
{
    /// <summary>
    /// 包的控制器:发放部分
    /// </summary>
    public partial class PackageController : BaseController
    {
        [Description("发放管理页面")]
        [ViewPage]
        public ActionResult FIndex()
        {
            return View();
        }

        [Description("发放列表页面")]
        [ViewPage]
        public ActionResult FList(string id)
        {
            return View();
        }

        [Description("物品交接记录页面")]
        [ViewPage]
        public ActionResult FRecord()
        {
            return View();
        }

        [Description("库存物品明细")]
        [Function(ButtonID = "btnInventory")]
        public ActionResult FInventorys()
        {
            return View();
        }

        [Description("未归还物品明细")]
        [Function(ButtonID = "btnNoReturn")]
        public ActionResult FNoReturns(string id)
        {
            this.ViewData["baomc"] = id == null ? "" : (DictionaryManager.Get(id) == null ? "" : DictionaryManager.Get(id).Name);
            return View();
        }

        [Description("新增发放")]
        [Function(ButtonID = "btnAdd")]
        public ActionResult FAdd()
        {
            this.ViewData["entity"] = new Package();
            return View();
        }

        [Description("确认发放")]
        [Function(ButtonID = "btnSave")]
        public ActionResult FSave()
        {
            return View();
        }

        [Description("删除发放")]
        [Function(ButtonID = "btnDelete")]
        public ActionResult FDelete(IList<string> idList)
        {
            MessageInfo msg = new MessageInfo();
            msg.IsSuccess = true;
            msg.Message = "删除成功";
            PackageManager.Delete(idList.Cast<object>().ToList());
            return Json(msg);
        }

        [Description("保存发放")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FSave(Package entity)
        {
            MessageInfo msg = new MessageInfo();
            if (string.IsNullOrEmpty(entity.Id))//确认发放
            {
                string strLingYKS = Request["LingYKS"];
                string strLingYR = Request["LingYR"];
                string strShiYR = Request["ShiYR"];
                if (!string.IsNullOrEmpty(strLingYKS)
                    && !string.IsNullOrEmpty(strLingYR)
                    && !string.IsNullOrEmpty(strShiYR))
                {
                    if (!HasLingYKS(strLingYKS))
                    {
                        msg.IsSuccess = false;
                        msg.Message = "发放失败，该领用科室不存在";
                        return Json(msg);
                    }
                    else if (!HasLingYR(strLingYR))
                    {
                        msg.IsSuccess = false;
                        msg.Message = "发放失败，该领用人不存在";
                        return Json(msg);
                    }
                    else if (!HasLingYR(strShiYR))
                    {
                        msg.IsSuccess = false;
                        msg.Message = "发放失败，该使用人不存在";
                        return Json(msg);
                    }

                    if (Cache.GetSessionCache("HospUser") != null)
                    {
                        HospUser user = (HospUser)Cache.GetSessionCache("HospUser");
                        if (!PackageManager.SaveFangF(strLingYKS, strLingYR, strShiYR, user.Name))
                        {
                            msg.IsSuccess = false;
                            msg.Message = "确认发放失败!";
                            return Json(msg);
                        }                        
                    }
                    else
                    {
                        msg.IsSuccess = false;
                        msg.Message = "获取发放人信息失败";
                        return Json(msg);
                    }
                }
                else
                {
                    msg.IsSuccess = false;
                    msg.Message = "获取领用科室等参数失败！";
                    return Json(msg);
                }
            }
            else//修改
            {
                var model = PackageManager.Get(entity.Id);
                model.TiaoMH = entity.TiaoMH;
                model.BaoMC = entity.BaoMC;
                model.LingYKS = entity.LingYKS;
                model.LingYR = entity.LingYR;
                model.ShiYR = entity.ShiYR;
                PackageManager.Update(model);
            }
            msg.IsSuccess = true;
            msg.Message = "发放成功";
            return Json(msg, "text/html", JsonRequestBehavior.AllowGet);
        }

        public ActionResult FLoadAllByPage(string id, int page, int rows, string order, string sort)
        {
            long total = 0;
            IList<Package> ilist = GetPackages(id, page, rows, order, sort, out total).OrderByDescending(p=>p.FaFSJ).ToList();
            var list = ilist.Select(p => new
            {
                p.Id,
                p.FaFR,
                p.TiaoMH,
                p.ZhuangT,
                p.ShiXSJ,
                FaFRQ = string.IsNullOrEmpty(p.FaFSJ) == true ? string.Empty : DateTime.Parse(p.FaFSJ).ToString("yyyy-MM-dd"),
                FaFSJ = string.IsNullOrEmpty(p.FaFSJ) == true ? string.Empty : DateTime.Parse(p.FaFSJ).ToString("HH:mm:ss"),
                BaoMC = DictionaryManager.Get(p.BaoMC) == null ? "" : DictionaryManager.Get(p.BaoMC).Name,
                LingYKS = DictionaryManager.Get(p.LingYKS) == null ? "" : DictionaryManager.Get(p.LingYKS).Name,
                LingYR = DictionaryManager.Get(p.LingYR) == null ? "" : DictionaryManager.Get(p.LingYR).Name,
                ShiYR = DictionaryManager.Get(p.ShiYR) == null ? "" : DictionaryManager.Get(p.ShiYR).Name,
                p.BaoZR,
                p.MieJR
            });
            return this.JsonFormat(new GridData { total = total, rows = list.ToList() });
        }

        public ActionResult FLoadAllPackgeView()
        {
            IList<V_Package> list = PackageManager.GetAllPackageView();
            List<PackageViewGrid> gridList = ConvertToPackageViewGrid(list);
            return this.JsonFormat(new GridData { total = gridList.LongCount(), rows = gridList.ToList() });
        }

        //库存
        public ActionResult FLoadAllInventorys()
        {
            IList<Package> ilist = PackageManager.GetInventory("");
            var list = ilist.Select(p => new
            {
                p.TiaoMH,
                BaoMC = DictionaryManager.Get(p.BaoMC) == null ? "" : DictionaryManager.Get(p.BaoMC).Name,
                YouXQ = p.YouXQ == null ? "" : p.YouXQ,
                p.BaoZR,
                MieJR = p.MieJR == null ? "" : p.MieJR,
                MieJSJ = p.MieJSJ == null ? "" : DateTime.Parse(p.MieJSJ).ToString("yyyy-MM-dd"),
                MieJGH = p.MieJGH == null ? "" : (DictionaryManager.Get(p.MieJGH) == null ? "" : DictionaryManager.Get(p.MieJGH).Name),
                MieJGC = p.MieJGC == null ? "" : (DictionaryManager.Get(p.MieJGC) == null ? "" : DictionaryManager.Get(p.MieJGC).Name),
                ShiXSJ = p.ShiXSJ == null ? "" : DateTime.Parse(p.ShiXSJ).ToString("yyyy-MM-dd")
            });
            return this.JsonFormat(new GridData { total = list.LongCount(), rows = list.ToList() });
        }

        //未归还
        public ActionResult FLoadAllNoReturns(string id)
        {
            IList<Package> ilist = PackageManager.GetNoReurns(id);
            var list = ilist.Select(p => new
            {
                p.TiaoMH,
                BaoMC = DictionaryManager.Get(p.BaoMC) == null ? "" : DictionaryManager.Get(p.BaoMC).Name,
                LingYKS = p.LingYKS == null ? "" : (DictionaryManager.Get(p.LingYKS) == null ? "" : DictionaryManager.Get(p.LingYKS).Name),
                LingYR = p.LingYR == null ? "" : (DictionaryManager.Get(p.LingYR) == null ? "" : DictionaryManager.Get(p.LingYR).Name),
                ShiYR = p.ShiYR == null ? "" : (DictionaryManager.Get(p.ShiYR) == null ? "" : DictionaryManager.Get(p.ShiYR).Name),
                FaFSJ = p.FaFSJ == null ? "" : DateTime.Parse(p.FaFSJ).ToString("yyyy-MM-dd"),
                p.FaFR,
                ShiXSJ = p.ShiXSJ == null ? "" : DateTime.Parse(p.ShiXSJ).ToString("yyyy-MM-dd"),
            });           
            return this.JsonFormat(new GridData { total = list.LongCount(), rows = list.ToList() });
        }

        public ActionResult GetOffices(string id)
        {
            //领用科室
            string strKeyword = Request["q"];
            IList<Dictionary> ilist = DictionaryManager.LoadAllByCategoryCode("lingyks");
            IEnumerable<Dictionary> query;
            if (!string.IsNullOrEmpty(strKeyword))
            {
                strKeyword = strKeyword.ToLower();
                query = ilist.Where(d =>
                {
                    {
                        string InputCode1 = string.IsNullOrEmpty(d.InputCode1) == true ? "" : d.InputCode1.ToLower();
                        string InputCode2 = string.IsNullOrEmpty(d.InputCode2) == true ? "" : d.InputCode2.ToLower();
                        string InputCode3 = string.IsNullOrEmpty(d.InputCode3) == true ? "" : d.InputCode3.ToLower();
                        return (d.Code.Contains(strKeyword) 
                            || d.Name.Contains(strKeyword)
                            || InputCode1.Contains(strKeyword) 
                            || InputCode2.Contains(strKeyword) 
                            || InputCode2.Contains(strKeyword));
                    }
                });
            }
            else
            {
                query = ilist;
            }
            return this.JsonFormat(new GridData { total = query.LongCount(), rows = query.ToList() });
        }

        public ActionResult GetRecipients(string id)
        {
            //领用人
            string strKeyword = Request["q"];
            IList<Dictionary> ilist = DictionaryManager.LoadAllByCategoryCode("lingyr");
            IEnumerable<Dictionary> query;
            if (!string.IsNullOrEmpty(strKeyword))
            {
                strKeyword = strKeyword.ToLower();
                query = ilist.Where(d =>
                {
                    {
                        string InputCode1 = string.IsNullOrEmpty(d.InputCode1) == true ? "" : d.InputCode1.ToLower();
                        string InputCode2 = string.IsNullOrEmpty(d.InputCode2) == true ? "" : d.InputCode2.ToLower();
                        string InputCode3 = string.IsNullOrEmpty(d.InputCode3) == true ? "" : d.InputCode3.ToLower();
                        return (d.Code.Contains(strKeyword)
                            || d.Name.Contains(strKeyword)
                            || InputCode1.Contains(strKeyword)
                            || InputCode2.Contains(strKeyword)
                            || InputCode2.Contains(strKeyword));
                    }
                });
            }
            else
            {
                query = ilist;
            }
            return this.JsonFormat(new GridData { total = query.LongCount(), rows = query.ToList() });
        }

        public ActionResult GetUsers(string id)
        {
            //使用人
            string strKeyword = Request["q"];
            IList<Dictionary> ilist = DictionaryManager.LoadAllByCategoryCode("lingyr");
            IEnumerable<Dictionary> query;
            if (!string.IsNullOrEmpty(strKeyword))
            {
                strKeyword = strKeyword.ToLower();
                query = ilist.Where(d =>
                {
                    {
                        string InputCode1 = string.IsNullOrEmpty(d.InputCode1) == true ? "" : d.InputCode1.ToLower();
                        string InputCode2 = string.IsNullOrEmpty(d.InputCode2) == true ? "" : d.InputCode2.ToLower();
                        string InputCode3 = string.IsNullOrEmpty(d.InputCode3) == true ? "" : d.InputCode3.ToLower();
                        return (d.Code.Contains(strKeyword)
                            || d.Name.Contains(strKeyword)
                            || InputCode1.Contains(strKeyword)
                            || InputCode2.Contains(strKeyword)
                            || InputCode2.Contains(strKeyword));
                    }
                });
            }
            else
            {
                query = ilist;
            }
            return this.JsonFormat(new GridData { total = query.LongCount(), rows = query.ToList() });
        }

        //获取灭菌的包名称
        public ActionResult GetMBaoMC(string id)
        {
            Dictionary dictionary = DictionaryManager.GetByTiaoMH(id, 2);
            if (dictionary == null)
            {
                dictionary = new Dictionary();
                dictionary.Id = string.Empty;
                dictionary.Name = string.Empty;
            }
            else
            {
                var model = PackageManager.GetByTiaoMH(id);
                model.ZhuangT = 30;
                PackageManager.Update(model);
            }
            return this.JsonFormat(new { id = dictionary.Id, text = dictionary.Name });
        }

        private List<PackageViewGrid> ConvertToPackageViewGrid(IList<V_Package> list)
        {
            List<PackageViewGrid> gridList = new List<PackageViewGrid>();
            foreach (V_Package tempPackageView in list)
            {
                PackageViewGrid tempGrid = gridList.Find(p => p.BaoBH == tempPackageView.BaoBH);
                if (tempGrid != null)
                {
                    //库存数量
                    if (tempPackageView.ZhuangT == 1 //包装
                        || tempPackageView.ZhuangT == 2 //灭菌
                        || tempPackageView.ZhuangT == 20 //待灭菌
                        || tempPackageView.ZhuangT == 30)//待发放
                    {
                        tempGrid.KuCL += 1;
                    }
                    //未归还数量
                    else if (tempPackageView.ZhuangT == 3 //已经发放
                        || tempPackageView.ZhuangT == 40)//待回收
                    {
                        tempGrid.WeiGHSL += 1;
                        if (tempPackageView.ShiFDH)//兑换
                        {
                            tempGrid.DuiHSL += 1;
                        }
                    }
                }
                else
                {
                    tempGrid = new PackageViewGrid();
                    tempGrid.BaoBH = tempPackageView.BaoBH;
                    tempGrid.BaoMC = tempPackageView.BaoMC;
                    //库存数量
                    if (tempPackageView.ZhuangT == 1 //包装
                        || tempPackageView.ZhuangT == 2 //灭菌
                        || tempPackageView.ZhuangT == 20 //待灭菌
                        || tempPackageView.ZhuangT == 30)//待发放
                    {
                        tempGrid.KuCL = 1;
                    }
                    //未归还数量
                    else if (tempPackageView.ZhuangT == 3 //已经发放
                        || tempPackageView.ZhuangT == 40)//待回收
                    {
                        tempGrid.WeiGHSL = 1;
                        if (tempPackageView.ShiFDH)//兑换
                        {
                            tempGrid.DuiHSL = 1;
                        }
                    }
                    else
                    {
                        tempGrid.KuCL = 0;
                        tempGrid.WeiGHSL = 0;
                        tempGrid.DuiHSL = 0;
                    }
                    gridList.Add(tempGrid);
                }
            }
            return gridList;
        }

        /// <summary>
        /// 根据编号效验领用科室是否存在
        /// </summary>
        /// <param name="LingYKS">条目中领用科室对应的ID号</param>
        /// <returns></returns>
        private bool HasLingYKS(string LingYKS)
        {
            var tempList = DictionaryManager.LoadAllByCategoryCode("lingyks").Where(p => p.Id.ToLower() == LingYKS.ToLower());
            int count = tempList.Count();
            return count > 0;
        }       

        /// <summary>
        /// 根据编号效验‘领用人/使用人’是否存在
        /// </summary>
        /// <param name="LingYR">条目中‘领用人/使用人’对应的ID号</param>
        /// <returns></returns>
        private bool HasLingYR(string LingYR)
        {
            var tempList = DictionaryManager.LoadAllByCategoryCode("lingyr").Where(p => p.Id.ToLower() == LingYR.ToLower());
            int count = tempList.Count();
            return count > 0;
        }

    }
}
